from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app.api import deps
from app.schemas import customer_passenger as schemas
from app.database.models.erp import CustomerPassenger, CustomerProfile
from app.database.models.base import User

router = APIRouter()

@router.get("/by-customer/{customer_profile_id}", response_model=List[schemas.CustomerPassenger])
def list_customer_passengers(
    customer_profile_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取指定客户的所有乘客信息"""
    try:
        # 检查客户是否存在
        customer = db.query(CustomerProfile).filter(CustomerProfile.ID == customer_profile_id).first()
        if not customer:
            raise HTTPException(status_code=404, detail="Customer not found")

        # 检查权限
        if current_user.role != "admin" and customer.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 获取乘客列表
        passengers = db.query(CustomerPassenger).filter(
            CustomerPassenger.customer_profile_id == customer_profile_id
        ).all()
        return passengers
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/", response_model=schemas.CustomerPassenger)
def create_customer_passenger(
    *,
    db: Session = Depends(deps.get_db),
    passenger_in: schemas.CustomerPassengerCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新的乘客信息"""
    try:
        # 检查客户是否存在
        customer = db.query(CustomerProfile).filter(
            CustomerProfile.ID == passenger_in.customer_profile_id
        ).first()
        if not customer:
            raise HTTPException(status_code=404, detail="Customer not found")

        # 检查权限
        if current_user.role != "admin" and customer.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 创建乘客记录
        passenger = CustomerPassenger(**passenger_in.dict())
        db.add(passenger)
        db.commit()
        db.refresh(passenger)
        return passenger
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{passenger_id}", response_model=schemas.CustomerPassenger)
def update_customer_passenger(
    *,
    db: Session = Depends(deps.get_db),
    passenger_id: int,
    passenger_in: schemas.CustomerPassengerUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新乘客信息"""
    try:
        # 获取乘客记录
        passenger = db.query(CustomerPassenger).filter(CustomerPassenger.ID == passenger_id).first()
        if not passenger:
            raise HTTPException(status_code=404, detail="Passenger not found")

        # 检查权限
        customer = db.query(CustomerProfile).filter(
            CustomerProfile.ID == passenger.customer_profile_id
        ).first()
        if current_user.role != "admin" and customer.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 更新乘客信息
        for field, value in passenger_in.dict(exclude_unset=True).items():
            setattr(passenger, field, value)

        db.add(passenger)
        db.commit()
        db.refresh(passenger)
        return passenger
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{passenger_id}")
def delete_customer_passenger(
    *,
    db: Session = Depends(deps.get_db),
    passenger_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除乘客信息"""
    try:
        # 获取乘客记录
        passenger = db.query(CustomerPassenger).filter(CustomerPassenger.ID == passenger_id).first()
        if not passenger:
            raise HTTPException(status_code=404, detail="Passenger not found")

        # 检查权限
        customer = db.query(CustomerProfile).filter(
            CustomerProfile.ID == passenger.customer_profile_id
        ).first()
        if current_user.role != "admin" and customer.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 删除乘客记录
        db.delete(passenger)
        db.commit()
        return {"ok": True}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 